<?php

namespace app\api\controller;

use app\api\model\Lottery;
use app\api\model\Participant;
use app\Request;

class Activity extends Authorization
{
    public function getActivityList(Request $request){
        $query = (new Lottery())->select();
        $data = [];
        foreach ($query as $k=>$v){
            $existUser = (new Participant())->where(['lottery_id'=>$v['id'],'users_id'=>$request->user->user_id])->find();
            if ($existUser){$v['exist']=true;}else{$v['exist']=false;}
            $data[] = $v;
        }
        return $this->success('ok',['data'=>$data]);
    }
    public function joinActivity(Request $request){
        $aid = $request->param('aid','');
        if(empty($aid)) return $this->error('非法操作');

        $existUser = (new Participant())->where(['lottery_id'=>$aid,'users_id'=>$request->user->user_id])->find();
        if($existUser) return $this->error('已经报名了');
        $lottery = (new Lottery())->find($aid);
        $now = date('Y-m-d H:i:s');
        if (strtotime($now) < strtotime($lottery['start_time']) || strtotime($now) > strtotime($lottery['end_time'])) return $this->error('未在报名时间范围，报名失败');
        $data = [
            'team'      =>  AttrToTeamValue($request->user->data->team),
            'nickname'  =>  $request->user->data->nickname,
            'users_id'     =>  $request->user->user_id,
            'lottery_id'=>  $aid
        ];
        $query = (new Participant())->save($data);
        if (!$query) return $this->error('参与失败');
        return $this->success('报名成功！');
    }
    public function exitActivity(Request $request){
        $aid = $request->param('aid','');
        if(empty($aid)) return $this->error('非法操作');

        $query = (new Participant())->where(['lottery_id'=>$aid,'users_id'=>$request->user->user_id])->delete();
        if (!$query) return $this->error('服务器错误');
        return $this->success('已取消报名！');
    }
}